import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { toast } from 'sonner';
import {
  Search,
  Filter,
  X,
  Calendar,
  Tag,
  User,
  Activity,
  AlertCircle,
  CheckCircle,
  Clock,
  Zap
} from 'lucide-react';

// 搜索过滤器类型
interface SearchFilter {
  id: string;
  type: 'text' | 'select' | 'date' | 'status' | 'user' | 'category';
  label: string;
  value: any;
  options?: { label: string; value: string }[];
}

// 搜索结果类型
interface SearchResult {
  id: string;
  type: 'activity' | 'user' | 'system' | 'widget' | 'notification';
  title: string;
  description: string;
  timestamp?: string;
  status?: 'success' | 'warning' | 'error' | 'info';
  category?: string;
  tags?: string[];
  relevance: number;
}

interface AdvancedSearchProps {
  isOpen: boolean;
  onClose: () => void;
  onResultSelect?: (result: SearchResult) => void;
  searchData?: any;
}

/**
 * 高级搜索和过滤组件
 * 提供全局搜索和智能过滤功能
 */
export const AdvancedSearch: React.FC<AdvancedSearchProps> = ({
  isOpen,
  onClose,
  onResultSelect,
  searchData
}) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [filters, setFilters] = useState<SearchFilter[]>([]);
  const [results, setResults] = useState<SearchResult[]>([]);
  const [isSearching, setIsSearching] = useState(false);
  const [selectedFilters, setSelectedFilters] = useState<string[]>([]);
  const [sortBy, setSortBy] = useState<'relevance' | 'date' | 'type'>('relevance');

  // 可用的过滤器配置
  const availableFilters: Omit<SearchFilter, 'id' | 'value'>[] = [
    {
      type: 'select',
      label: '内容类型',
      options: [
        { label: '活动记录', value: 'activity' },
        { label: '用户数据', value: 'user' },
        { label: '系统状态', value: 'system' },
        { label: '小部件', value: 'widget' },
        { label: '通知', value: 'notification' }
      ]
    },
    {
      type: 'select',
      label: '状态',
      options: [
        { label: '成功', value: 'success' },
        { label: '警告', value: 'warning' },
        { label: '错误', value: 'error' },
        { label: '信息', value: 'info' }
      ]
    },
    {
      type: 'select',
      label: '时间范围',
      options: [
        { label: '今天', value: 'today' },
        { label: '最近一周', value: 'week' },
        { label: '最近一月', value: 'month' },
        { label: '最近一年', value: 'year' }
      ]
    },
    {
      type: 'select',
      label: '分类',
      options: [
        { label: '用户管理', value: 'user-management' },
        { label: '系统监控', value: 'system-monitoring' },
        { label: '数据分析', value: 'analytics' },
        { label: '安全审计', value: 'security' }
      ]
    }
  ];

  // 模拟搜索数据
  const mockSearchData: SearchResult[] = [
    {
      id: '1',
      type: 'activity',
      title: '用户登录成功',
      description: '管理员用户 admin@example.com 成功登录系统',
      timestamp: '2分钟前',
      status: 'success',
      category: 'user-management',
      tags: ['登录', '管理员'],
      relevance: 0.95
    },
    {
      id: '2',
      type: 'system',
      title: 'CPU 使用率警告',
      description: '服务器 CPU 使用率达到 85%，建议检查系统负载',
      timestamp: '5分钟前',
      status: 'warning',
      category: 'system-monitoring',
      tags: ['CPU', '性能', '警告'],
      relevance: 0.88
    },
    {
      id: '3',
      type: 'user',
      title: '新用户注册',
      description: '用户 john.doe@example.com 完成注册流程',
      timestamp: '10分钟前',
      status: 'info',
      category: 'user-management',
      tags: ['注册', '新用户'],
      relevance: 0.82
    },
    {
      id: '4',
      type: 'widget',
      title: '数据统计小部件',
      description: '显示用户数量、消息数量等关键指标',
      status: 'info',
      category: 'analytics',
      tags: ['统计', '小部件'],
      relevance: 0.75
    },
    {
      id: '5',
      type: 'notification',
      title: '系统维护通知',
      description: '系统将于今晚 23:00 进行例行维护',
      timestamp: '1小时前',
      status: 'info',
      category: 'system-monitoring',
      tags: ['维护', '通知'],
      relevance: 0.70
    }
  ];

  /**
   * 执行搜索
   */
  const performSearch = async () => {
    if (!searchQuery.trim() && filters.length === 0) {
      setResults([]);
      return;
    }

    setIsSearching(true);
    
    try {
      // 模拟搜索延迟
      await new Promise(resolve => setTimeout(resolve, 800));
      
      let filteredResults = [...mockSearchData];
      
      // 文本搜索过滤
      if (searchQuery.trim()) {
        filteredResults = filteredResults.filter(item => 
          item.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
          item.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
          item.tags?.some(tag => tag.toLowerCase().includes(searchQuery.toLowerCase()))
        );
      }
      
      // 应用过滤器
      filters.forEach(filter => {
        if (filter.value) {
          switch (filter.type) {
            case 'select':
              if (filter.label === '内容类型') {
                filteredResults = filteredResults.filter(item => item.type === filter.value);
              } else if (filter.label === '状态') {
                filteredResults = filteredResults.filter(item => item.status === filter.value);
              } else if (filter.label === '分类') {
                filteredResults = filteredResults.filter(item => item.category === filter.value);
              }
              break;
          }
        }
      });
      
      // 排序
      filteredResults.sort((a, b) => {
        switch (sortBy) {
          case 'relevance':
            return b.relevance - a.relevance;
          case 'date':
            return (b.timestamp || '').localeCompare(a.timestamp || '');
          case 'type':
            return a.type.localeCompare(b.type);
          default:
            return 0;
        }
      });
      
      setResults(filteredResults);
    } catch (error) {
      toast.error('搜索失败，请重试');
    } finally {
      setIsSearching(false);
    }
  };

  /**
   * 添加过滤器
   */
  const addFilter = (filterConfig: Omit<SearchFilter, 'id' | 'value'>) => {
    const newFilter: SearchFilter = {
      ...filterConfig,
      id: `filter-${Date.now()}`,
      value: ''
    };
    setFilters(prev => [...prev, newFilter]);
  };

  /**
   * 移除过滤器
   */
  const removeFilter = (filterId: string) => {
    setFilters(prev => prev.filter(f => f.id !== filterId));
  };

  /**
   * 更新过滤器值
   */
  const updateFilter = (filterId: string, value: any) => {
    setFilters(prev => prev.map(f => 
      f.id === filterId ? { ...f, value } : f
    ));
  };

  /**
   * 获取状态图标
   */
  const getStatusIcon = (status?: string) => {
    switch (status) {
      case 'success':
        return <CheckCircle className="w-4 h-4 text-green-500" />;
      case 'warning':
        return <AlertCircle className="w-4 h-4 text-yellow-500" />;
      case 'error':
        return <AlertCircle className="w-4 h-4 text-red-500" />;
      case 'info':
        return <Activity className="w-4 h-4 text-blue-500" />;
      default:
        return <Clock className="w-4 h-4 text-gray-500" />;
    }
  };

  /**
   * 获取类型图标
   */
  const getTypeIcon = (type: string) => {
    switch (type) {
      case 'user':
        return <User className="w-4 h-4" />;
      case 'activity':
        return <Activity className="w-4 h-4" />;
      case 'system':
        return <Zap className="w-4 h-4" />;
      case 'widget':
        return <Tag className="w-4 h-4" />;
      case 'notification':
        return <AlertCircle className="w-4 h-4" />;
      default:
        return <Search className="w-4 h-4" />;
    }
  };

  // 监听搜索查询和过滤器变化
  useEffect(() => {
    const debounceTimer = setTimeout(() => {
      performSearch();
    }, 300);
    
    return () => clearTimeout(debounceTimer);
  }, [searchQuery, filters, sortBy]);

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-4xl max-h-[80vh] overflow-hidden flex flex-col">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Search className="w-5 h-5" />
            高级搜索
          </DialogTitle>
          <DialogDescription>
            搜索仪表盘中的所有内容，使用过滤器精确定位
          </DialogDescription>
        </DialogHeader>
        
        <div className="flex-1 overflow-hidden flex flex-col space-y-4">
          {/* 搜索输入 */}
          <div className="space-y-2">
            <Label>搜索关键词</Label>
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
              <Input
                placeholder="输入搜索关键词..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>

          {/* 过滤器管理 */}
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <Label>过滤器</Label>
              <Select onValueChange={(value) => {
                const filterConfig = availableFilters.find(f => f.label === value);
                if (filterConfig) addFilter(filterConfig);
              }}>
                <SelectTrigger className="w-40">
                  <SelectValue placeholder="添加过滤器" />
                </SelectTrigger>
                <SelectContent>
                  {availableFilters.map((filter) => (
                    <SelectItem key={filter.label} value={filter.label}>
                      <div className="flex items-center gap-2">
                        <Filter className="w-4 h-4" />
                        {filter.label}
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            
            {/* 活动过滤器 */}
            {filters.length > 0 && (
              <div className="space-y-2">
                {filters.map((filter) => (
                  <div key={filter.id} className="flex items-center gap-2 p-2 border rounded-lg">
                    <Label className="text-sm font-medium min-w-[80px]">
                      {filter.label}:
                    </Label>
                    {filter.type === 'select' && filter.options && (
                      <Select 
                        value={filter.value} 
                        onValueChange={(value) => updateFilter(filter.id, value)}
                      >
                        <SelectTrigger className="flex-1">
                          <SelectValue placeholder={`选择${filter.label}`} />
                        </SelectTrigger>
                        <SelectContent>
                          {filter.options.map((option) => (
                            <SelectItem key={option.value} value={option.value}>
                              {option.label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    )}
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => removeFilter(filter.id)}
                    >
                      <X className="w-4 h-4" />
                    </Button>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* 排序选项 */}
          <div className="flex items-center gap-4">
            <Label>排序方式:</Label>
            <Select value={sortBy} onValueChange={(value: 'relevance' | 'date' | 'type') => setSortBy(value)}>
              <SelectTrigger className="w-32">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="relevance">相关性</SelectItem>
                <SelectItem value="date">时间</SelectItem>
                <SelectItem value="type">类型</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* 搜索结果 */}
          <div className="flex-1 overflow-auto space-y-2">
            {isSearching ? (
              <div className="flex items-center justify-center py-8">
                <div className="flex items-center space-x-2">
                  <div className="w-4 h-4 border-2 border-primary border-t-transparent rounded-full animate-spin" />
                  <span>搜索中...</span>
                </div>
              </div>
            ) : results.length > 0 ? (
              <div className="space-y-2">
                <div className="text-sm text-muted-foreground">
                  找到 {results.length} 个结果
                </div>
                {results.map((result) => (
                  <div
                    key={result.id}
                    className="p-3 border rounded-lg hover:bg-gray-50 cursor-pointer transition-colors"
                    onClick={() => {
                      onResultSelect?.(result);
                      toast.success(`已选择: ${result.title}`);
                    }}
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          {getTypeIcon(result.type)}
                          <span className="font-medium">{result.title}</span>
                          {result.status && getStatusIcon(result.status)}
                        </div>
                        <p className="text-sm text-muted-foreground mb-2">
                          {result.description}
                        </p>
                        <div className="flex items-center gap-2">
                          {result.timestamp && (
                            <Badge variant="outline" className="text-xs">
                              <Clock className="w-3 h-3 mr-1" />
                              {result.timestamp}
                            </Badge>
                          )}
                          {result.category && (
                            <Badge variant="secondary" className="text-xs">
                              {result.category}
                            </Badge>
                          )}
                          {result.tags?.map((tag) => (
                            <Badge key={tag} variant="outline" className="text-xs">
                              {tag}
                            </Badge>
                          ))}
                        </div>
                      </div>
                      <div className="text-xs text-muted-foreground ml-4">
                        {Math.round(result.relevance * 100)}% 匹配
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ) : searchQuery || filters.length > 0 ? (
              <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
                <Search className="w-12 h-12 mb-2" />
                <p>未找到匹配的结果</p>
                <p className="text-sm">尝试调整搜索关键词或过滤条件</p>
              </div>
            ) : (
              <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
                <Search className="w-12 h-12 mb-2" />
                <p>输入关键词开始搜索</p>
                <p className="text-sm">或添加过滤器精确查找</p>
              </div>
            )}
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={onClose}>
            关闭
          </Button>
          <Button onClick={() => {
            setSearchQuery('');
            setFilters([]);
            setResults([]);
          }}>
            清除搜索
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};